<?php

namespace App\Http\Controllers\Admin\Config;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use App\Models\Banner;
use Validator;

class BannerController extends AdminController
{
    function getLists(Request $request){
    	$pageIndex = (int)$request->input('page') ?  $request->input('page') : 1;
        $length    = (int)$request->input('length') ?  $request->input('length') : 10;
        $start     = ($pageIndex-1)*$length;

    	$where = [];
        $bannerModel = Banner::where($where);
        if($name=$request->input('name')){
            $bannerModel = $bannerModel->where('name', 'like', "%$name%");
        }

    	$data['total'] = $bannerModel->count();
    	if($data['total']>0){
    		$data['result'] = $bannerModel->orderBy('name','desc')->orderBy('updated_at','desc')->skip($start)->take($length)->get()->toArray();
    	}
    	$this->ajaxJson(0,'',$data);
    }

    /**
     * 获取单个数据
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function getOne($id){
    	$banner = $this->_get_one($id);
    	$this->ajaxJson(0,'',$banner);
    }

    

    /**
     * 更新数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function postUpdate(Request $request){
    	$data = $request->all();
    	$validator = $this->formValidator($data);
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
       	if($data['id']){
       		$banner = $this->_get_one($data['id']);
       	}else{
       		$banner = new Banner();
       	}
       	$banner->name = $data['name'];
       	$banner->link = $data['link'];
       	$banner->pic = $data['pic'];
       	$banner->save();
       	$this->ajaxJson(0,'更新成功');
    }

    function deleteOne($id){
		$banner = $this->_get_one($id);
		$banner->delete();
    	$this->ajaxJson(0,'删除成功');
    }

    /**
     * 表单验证
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    private function formValidator(array $data){
        $attribute =  array(
            'pic' => '图片',
        );

        $message  = array(
            'required' => ':attribute必须上传',
        );
        return Validator::make($data, [
            'pic' => 'bail|required',
        ],$message,$attribute);
    }

    private function _get_one($id){
    	$banner = Banner::find($id);
    	if(!$banner){
    		$this->ajaxJson(1,'数据不存在,请刷新页面');
    	}
    	return $banner;
    }
}
